package com.cheng.learn.designmode.singleton;

/**
 * @description: java单例设计
 * @author: ChengHaiZhu
 * @create: 2021-03-10 14:05
 **/
public class Singleton {
    /**
     * volatile 关键字，禁止重排序
     */
    private static volatile Singleton singleton;

    /**
     * 私有构造方法
     */
    private Singleton(){}

    /**
     * 双检锁实现单例模式
     * @return Singleton
     */
    public static Singleton getInstance(){
        // 双检锁
        if(singleton != null){
            synchronized(Singleton.class){
                // 避免重复创建实例
                if(singleton != null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

}
